<template>
  <div class="parking-container">
    <el-card class="parking-card">
      <template #header>
        <div class="card-header">
          <h2>智能停车场管理</h2>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="摄像头识别" name="camera">
              <div class="video-container">
                <video ref="video" autoplay class="video"></video>
                <canvas ref="canvas" style="display: none;"></canvas>
              </div>
              <div class="button-group">
                <el-button type="primary" @click="startCamera" :disabled="isCameraStarted">
                  开启摄像头
                </el-button>
                <el-button type="success" @click="capturePlate" :disabled="!isCameraStarted">
                  识别车牌
                </el-button>
                <el-button type="primary" @click="handleEntry" :disabled="!isCameraStarted">
                  登记入场
                </el-button>
                <el-button type="danger" @click="handleExit" :disabled="!isCameraStarted">
                  登记出场
                </el-button>
                <el-button type="warning" @click="queryStatus" :disabled="!currentPlate">
                  查询状态
                </el-button>
                <!-- 新增关闭摄像头按钮 -->
                <el-button type="danger" @click="closeCamera" :disabled="!isCameraStarted">
                  关闭摄像头
                </el-button>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="手动输入" name="manual">
              <div class="manual-input">
                <el-input 
                  v-model="manualPlate" 
                  placeholder="请输入车牌号"
                  class="plate-input"
                >
                  <template #append>
                    <el-button @click="queryManual">查询</el-button>
                  </template>
                </el-input>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <!-- 识别结果展示区 -->
      <div v-loading="loading" class="result-area">
        <template v-if="currentPlate">
          <h3>识别结果：{{ currentPlate }}</h3>
          
          <!-- 停车信息展示 -->
          <template v-if="parkingInfo">
            <el-descriptions border>
              <el-descriptions-item label="车辆状态">
                <el-tag :type="parkingInfo.status === 0 ? 'success' : 'info'">
                  {{ parkingInfo.status === 0 ? '在场' : '已离场' }}
                </el-tag>
              </el-descriptions-item>
              
              <el-descriptions-item label="车辆类型">
                <el-tag :type="parkingInfo.vehicleType === 1 ? 'success' : 'warning'">
                  {{ parkingInfo.vehicleType === 1 ? '月租车' : '临时车' }}
                </el-tag>
              </el-descriptions-item>
              
              <el-descriptions-item label="入场时间">
                {{ formatTime(parkingInfo.startTime) }}
              </el-descriptions-item>
              
              <el-descriptions-item label="出场时间" v-if="parkingInfo.status === 1">
                {{ formatTime(parkingInfo.endTime) }}
              </el-descriptions-item>
              
              <el-descriptions-item label="停车费用" v-if="parkingInfo.status === 1">
                <template v-if="parkingInfo.vehicleType === 1">
                  <el-tag type="success">月租车免费</el-tag>
                </template>
                <template v-else>
                  ¥{{ parkingFee.toFixed(2) }}
                </template>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </template>

        <!-- 支付信息 -->
        <el-dialog
          v-model="showPayment"
          title="支付信息"
          width="400px"
          center
        >
          <div class="payment-info">
            <div class="qrcode-mock">
              <div class="amount">¥{{ parkingFee.toFixed(2) }}</div>
              <div class="order-id">订单号：{{ currentOrderId }}</div>
            </div>
            <el-button type="primary" @click="mockPayment">模拟支付</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllParkingRecords } from '../api/parkingRecord'
import request from '../utils/request'

// 状态变量
const activeTab = ref('camera')
const video = ref(null)
const canvas = ref(null)
const isCameraStarted = ref(false)
const loading = ref(false)
const currentPlate = ref('')
const manualPlate = ref('')
const parkingInfo = ref(null)
const parkingFee = ref(0)
const showPayment = ref(false)
const currentOrderId = ref('')

// 轮询定时器
let paymentPollTimer = null

// 开启摄像头
const startCamera = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ video: true })
    video.value.srcObject = stream
    isCameraStarted.value = true
  } catch (err) {
    ElMessage.error('无法访问摄像头，请检查权限设置')
    console.error('摄像头访问失败:', err)
  }
}

// 捕获图像
const captureImage = () => {
  if (!video.value || !canvas.value) return null
  
  const ctx = canvas.value.getContext('2d')
  canvas.value.width = video.value.videoWidth
  canvas.value.height = video.value.videoHeight
  ctx.drawImage(video.value, 0, 0)
  
  return canvas.value.toDataURL('image/jpeg').split(',')[1]
}

// 捕获并识别车牌
const capturePlate = async () => {
  const base64Image = captureImage()
  if (!base64Image) {
    ElMessage.error('无法捕获图像，请确保摄像头已开启')
    return
  }
  await recognizePlate(base64Image)
}

// 车牌识别请求
const recognizePlate = async (base64Image) => {
  try {
    loading.value = true
    console.log('发送识别请求...')
    const response = await request.post('http://localhost:9999/opencv-server/api/parking/status/recognize', {
      image: base64Image
    })

    console.log('收到响应:', response.status)
    const data = response.data
    console.log('识别结果:', data)
    
    if (data.success) {
      currentPlate.value = data.licensePlate
      ElMessage.success(`识别成功：${data.licensePlate}`)
      await checkVehicleType(data.licensePlate)
    } else {
      ElMessage.error(data.message || '识别失败')
    }
  } catch (error) {
    console.error('识别失败:', error)
    ElMessage.error(error.message || '识别失败，请重试')
  } finally {
    loading.value = false
  }
}

// 查询车辆类型
const checkVehicleType = async (plateNumber) => {
  if (!plateNumber) return
  
  loading.value = true
  try {
    console.log('查询车辆状态:', plateNumber)
    // 先查询停车状态
    const statusResponse = await request.get(`http://localhost:9999/opencv-server/api/parking/status/${plateNumber}`)
    console.log('状态查询响应:', statusResponse.status)
    
    const data = statusResponse.data
    console.log('状态查询结果:', data)
    if (data.success) {
      parkingInfo.value = data.record
      if (data.record) {
        ElMessage.success('查询到车辆记录')
      } else {
        ElMessage.info('未查询到在场记录')
      }
      return
    }
    
    // 如果没有停车记录，查询车辆信息
    console.log('查询车辆信息...')
    const vehicleResponse = await request.get(`http://localhost:9999/opencv-server/api/vehicle/check/${plateNumber}`)
    const vehicleData = vehicleResponse.data
    console.log('车辆信息:', vehicleData)
    if (vehicleData) {
      parkingInfo.value = {
        vehicleType: vehicleData.status === 1 && vehicleData.ownerId ? 1 : 0,
        status: null
      }
      ElMessage.info(parkingInfo.value.vehicleType === 1 ? '月租车辆' : '临时车辆')
    } else {
      parkingInfo.value = { vehicleType: 0, status: null }
      ElMessage.info('临时车辆')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理入场
const handleEntry = async () => {
  const base64Image = captureImage()
  if (!base64Image) {
    ElMessage.error('无法捕获图像，请确保摄像头已开启')
    return
  }
  
  loading.value = true
  try {
    console.log('发送入场请求...')
    const response = await request.post('http://localhost:9999/opencv-server/api/parking/entry/recognize', {
      image: base64Image
    })
    
    console.log('入场响应:', response.status)
    const data = response.data
    console.log('入场结果:', data)
    
    if (data.success) {
      ElMessage.success('入场登记成功')
      currentPlate.value = data.licensePlate
      parkingInfo.value = data.record
    } else {
      ElMessage.error(data.message || '入场登记失败')
    }
  } catch (error) {
    console.error('入场登记失败:', error)
    ElMessage.error('入场登记失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理出场
const handleExit = async () => {
  const base64Image = captureImage()
  if (!base64Image) {
    ElMessage.error('无法捕获图像，请确保摄像头已开启')
    return
  }
  
  loading.value = true
  try {
    console.log('发送出场请求...')
    const response = await request.post('http://localhost:9999/opencv-server/api/parking/exit/recognize', {
      image: base64Image
    })
    
    console.log('出场响应:', response.status)
    const data = response.data
    console.log('出场结果:', data)
    
    if (data.success) {
      ElMessage.success('出场登记成功')
      currentPlate.value = data.licensePlate
      parkingInfo.value = data.record
      parkingFee.value = data.fee
      
      if (data.record.vehicleType === 0 && data.fee > 0) {
        createPayment(data.record.orderId, data.fee)
      }
    } else {
      ElMessage.error(data.message || '出场登记失败')
    }
  } catch (error) {
    console.error('出场登记失败:', error)
    ElMessage.error('出场登记失败，请重试')
  } finally {
    loading.value = false
  }
}

// 创建支付订单
const createPayment = async (orderId, amount) => {
  try {
    console.log('创建支付订单:', orderId, amount)
    const response = await request.post(`http://localhost:9999/opencv-server/api/pay/create/${orderId}`)
    
    console.log('支付订单响应:', response.status)
    const data = response.data
    console.log('支付订单结果:', data)
    
    if (data.success) {
      currentOrderId.value = orderId
      showPayment.value = true
      startPaymentPoll(orderId)
    } else {
      ElMessage.error('创建支付订单失败：' + (data.message || '未知错误'))
    }
  } catch (error) {
    console.error('创建支付订单失败:', error)
    ElMessage.error('创建支付订单失败，请重试')
  }
}

// 支付状态
const startPaymentPoll = (orderId) => {
  if (paymentPollTimer) clearInterval(paymentPollTimer)
  
  paymentPollTimer = setInterval(async () => {
    try {
      const response = await request.get(`http://localhost:9999/opencv-server/api/pay/status/${orderId}`)
      const data = response.data
      
      if (data.success && data.paid) {
        clearInterval(paymentPollTimer)
        showPayment.value = false
        ElMessage.success('支付成功！')
      }
    } catch (error) {
      clearInterval(paymentPollTimer)
      console.error('查询支付状态失败:', error)
    }
  }, 2000)
}

// 模拟支付
const mockPayment = async () => {
  try {
    console.log('模拟支付:', currentOrderId.value)
    const response = await request.post(`http://localhost:9999/opencv-server/api/pay/mock/success/${currentOrderId.value}`)
    
    console.log('模拟支付响应:', response.status)
    const data = response.data
    console.log('模拟支付结果:', data)
    
    if (!data.success) {
      ElMessage.error('操作失败：' + (data.message || '未知错误'))
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 查询状态
const queryStatus = () => {
  if (currentPlate.value) {
    checkVehicleType(currentPlate.value)
  } else {
    ElMessage.warning('请先识别车牌')
  }
}

// 手动查询
const queryManual = async () => {
  if (!manualPlate.value) {
    ElMessage.warning('请输入车牌号')
    return
  }
  
  currentPlate.value = manualPlate.value
  await checkVehicleType(manualPlate.value)
}

// 关闭摄像头
const closeCamera = () => {
  if (video.value && video.value.srcObject) {
    video.value.srcObject.getTracks().forEach(track => track.stop())
    video.value.srcObject = null
    isCameraStarted.value = false
    ElMessage.success('摄像头已关闭')
  } else {
    ElMessage.info('摄像头未开启或已关闭')
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 组件销毁时清理
onUnmounted(() => {
  if (paymentPollTimer) {
    clearInterval(paymentPollTimer)
  }
  
  // 关闭摄像头
  if (video.value && video.value.srcObject) {
    video.value.srcObject.getTracks().forEach(track => track.stop())
  }
})

// 自动加载停车记录
if (activeTab.value === 'record') fetchParkingRecords()
watch(activeTab, (val) => {
  if (val === 'record') fetchParkingRecords()
})
</script>

<style scoped>
.parking-container {
  padding: 20px;
}

.parking-card {
  margin-bottom: 20px;
}

.card-header {
  h2 {
    margin: 0;
    padding-bottom: 20px;
  }
}

.video-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.video {
  width: 640px;
  height: 480px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-bottom: 20px;
}

.manual-input {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  
  .plate-input {
    width: 300px;
  }
}

.result-area {
  min-height: 200px;
}

.payment-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.qrcode-mock {
  width: 200px;
  height: 200px;
  border: 2px solid #dcdfe6;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  
  .amount {
    font-size: 24px;
    font-weight: bold;
    color: #409eff;
  }
  
  .order-id {
    margin-top: 10px;
    font-size: 14px;
    color: #909399;
  }
}
</style> 